<template>
  <el-dialog
    top="30px"
    width="800px"
    title="修改项目信息"
    append-to-body
    :close-on-click-modal="false"
    :before-close="beforeClose"
    :visible.sync="visible"
  >
    <el-form size="small" ref="form" label-width="150px" :model="form" :rules="rules">
      <el-form-item label="归属省" prop="address_name_pro">
        <el-input
          v-model="form.address_name_pro"
          class="form-control-ml"
          placeholder="请填写"
        ></el-input>
      </el-form-item>
      <el-form-item label="归属市" prop="address_name_city">
        <el-input
          v-model="form.address_name_city"
          class="form-control-ml"
          placeholder="请填写"
        ></el-input>
      </el-form-item>
      <el-form-item label="归属县" prop="address_name_county">
        <el-input
          v-model="form.address_name_county"
          class="form-control-ml"
          placeholder="请填写"
        ></el-input>
      </el-form-item>
      <el-form-item label="客户类型" prop="org_class">
        <select-farm-org
          v-model="form.org_class"
          class="form-control-ml"
          @select="handleOrgClassSelect"
        ></select-farm-org>
      </el-form-item>
      <el-form-item label="受保企业名称或贷款人姓名" prop="customer_name">
        <el-input
          v-model="form.customer_name"
          class="form-control-ml"
          placeholder="请填写"
        ></el-input>
      </el-form-item>
      <el-form-item label="受保企业联系人姓名" prop="corp_name">
        <el-input v-model="form.corp_name" class="form-control-ml" placeholder="请填写"></el-input>
      </el-form-item>
      <el-form-item label="受保企业联系人电话" prop="corp_phone">
        <el-input v-model="form.corp_phone" class="form-control-ml" placeholder="请填写"></el-input>
      </el-form-item>
      <el-form-item label="三证合一" prop="is_cert_merge">
        <c-radio-group
          v-model="form.is_cert_merge"
          :options="[
            { value: 1, label: '是' },
            { value: 0, label: '否' },
          ]"
        ></c-radio-group>
      </el-form-item>
      <el-form-item label="统一社会信用代码" prop="register_no" v-if="!isIndividual">
        <el-input
          v-model="form.register_no"
          class="form-control-ml"
          placeholder="请填写"
        ></el-input>
      </el-form-item>
      <el-form-item label="身份证号码" prop="id_card">
        <el-input v-model="form.id_card" class="form-control-ml" placeholder="请填写"></el-input>
      </el-form-item>
      <el-form-item label="行业" prop="parent_industrial_class">
        <el-input
          v-model="form.parent_industrial_class"
          class="form-control-ml"
          placeholder="请填写"
        ></el-input>
      </el-form-item>
      <el-form-item label="行业小类" prop="industrial_class">
        <el-input
          v-model="form.industrial_class"
          class="form-control-ml"
          placeholder="请填写"
        ></el-input>
      </el-form-item>
      <el-form-item label="销售收入" prop="sale_income">
        <el-input
          v-model="form.sale_income"
          type="number"
          class="form-control-ml"
          placeholder="请填写"
        >
          <span slot="append">万元</span>
        </el-input>
      </el-form-item>
      <el-form-item label="资产总额" prop="assets_funds">
        <el-input
          v-model="form.assets_funds"
          type="number"
          class="form-control-ml"
          placeholder="请填写"
        >
          <span slot="append">万元</span>
        </el-input>
      </el-form-item>
      <el-form-item label="从业人数" prop="emp_total">
        <el-input
          v-model="form.emp_total"
          type="number"
          class="form-control-ml"
          placeholder="请填写"
        >
          <span slot="append">人</span>
        </el-input>
      </el-form-item>
      <el-form-item label="担保业务类型" prop="loan_gua">
        <c-select
          v-model="form.loan_gua"
          class="form-control-ml"
          number-key
          :options="enumLoanGua"
        ></c-select>
      </el-form-item>
      <el-form-item label="放款银行名称" prop="bank_name">
        <el-input v-model="form.bank_name" class="form-control-ml" placeholder="请填写"></el-input>
      </el-form-item>
      <el-form-item label="贷款用途" prop="funds_use_dir">
        <el-input
          v-model="form.funds_use_dir"
          class="form-control-ml"
          placeholder="请填写"
        ></el-input>
      </el-form-item>
      <el-form-item label="担保（放款）金额" prop="warranty_amount">
        <el-input
          v-model="form.warranty_amount"
          type="number"
          class="form-control-ml"
          placeholder="请填写"
        >
          <span slot="append">万元</span>
        </el-input>
      </el-form-item>
      <el-form-item label="担保机构与受保企业合同号" prop="gua_contract">
        <el-input
          v-model="form.gua_contract"
          class="form-control-ml"
          placeholder="请填写"
        ></el-input>
      </el-form-item>
      <el-form-item label="放款日期" prop="load_date">
        <el-date-picker
          class="form-control-ml"
          v-model="form.load_date"
          :clearable="false"
          placeholder="放款日期"
          value-format="yyyy-MM-dd"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="还款日期" prop="load_end_date">
        <el-date-picker
          class="form-control-ml"
          v-model="form.load_end_date"
          :clearable="false"
          placeholder="还款日期"
          value-format="yyyy-MM-dd"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="年化费率" prop="warranty_rate">
        <el-input
          v-model="form.warranty_rate"
          type="number"
          class="form-control-ml"
          placeholder="请填写"
        >
          <span slot="append">%</span>
        </el-input>
      </el-form-item>
      <el-form-item label="已收担保费" prop="recieved_gua_fee">
        <el-input
          v-model="form.recieved_gua_fee"
          type="number"
          class="form-control-ml"
          placeholder="请填写"
        >
          <span slot="append">万元</span>
        </el-input>
      </el-form-item>
      <el-form-item label="收取其它费用（包括评审费等）" prop="other_cost">
        <el-input
          v-model="form.other_cost"
          type="number"
          class="form-control-ml"
          placeholder="请填写"
        >
          <span slot="append">万元</span>
        </el-input>
      </el-form-item>
      <el-form-item label="收取受保企业保证金" prop="income_margin">
        <el-input
          v-model="form.income_margin"
          type="number"
          class="form-control-ml"
          placeholder="请填写"
        >
          <span slot="append">万元</span>
        </el-input>
      </el-form-item>
      <el-form-item label="贷款银行与受保企业合同号" prop="ensurce_contract">
        <el-input
          v-model="form.ensurce_contract"
          class="form-control-ml"
          placeholder="请填写"
        ></el-input>
      </el-form-item>
      <el-form-item label="银行贷款利率" prop="load_rate">
        <el-input
          v-model="form.load_rate"
          type="number"
          class="form-control-ml"
          placeholder="请填写"
        >
          <span slot="append">%</span>
        </el-input>
      </el-form-item>
      <el-form-item label="担保机构向金融机构存入保证金" prop="repo_margin">
        <el-input
          v-model="form.repo_margin"
          type="number"
          class="form-control-ml"
          placeholder="请填写"
        >
          <span slot="append">万元</span>
        </el-input>
      </el-form-item>
      <el-form-item label="备注" prop="remark">
        <el-input v-model="form.remark" class="form-control-ml" placeholder="请填写"></el-input>
      </el-form-item>
      <el-form-item label="公司放款流水号" prop="loan_number">
        <el-input
          v-model="form.loan_number"
          class="form-control-ml"
          placeholder="请填写"
        ></el-input>
      </el-form-item>
      <el-form-item label="银行确认放款金额" prop="confirm_reply_funds">
        <el-input
          v-model="form.confirm_reply_funds"
          type="number"
          class="form-control-ml"
          placeholder="请填写"
        >
          <span slot="append">万元</span>
        </el-input>
      </el-form-item>
      <el-form-item>
        <el-button @click="handleSubmit" type="primary" class="btn-long" :loading="loading">
          保 存
        </el-button>
        <el-button @click="beforeClose" :disabled="loading">取 消</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>

<script>
import { idCardValidate, licenseValidate } from '@vimi/utils-tool'
import { phoneValidator } from '@/common/plugins/validator'
import { convertFormErrMsg } from '@/common/plugins/tools/convert'
import { enumLoanGua } from './mixins'

import SelectFarmOrg from '@/components/select/SelectFarmOrg'

export default {
  components: {
    SelectFarmOrg,
  },
  props: {
    visible: Boolean,
    formData: {
      type: Object,
      default: () => ({}),
    },
  },
  data() {
    const registerValidator = async (_, value, callback) => {
      if (!value) {
        return callback(new Error('请输入统一信用代码'))
      }

      if (!licenseValidate(value)) {
        return callback(new Error('统一信用代码格式错误'))
      }

      const isExist = await this.checkExist({
        'register_no.eq': value,
      })
      callback(isExist ? new Error('统一信用代码已存在') : void 0)
    }

    const idCardValidator = async (_, value, callback) => {
      if (!value) {
        return callback(new Error('请输入身份证号码'))
      }

      if (!idCardValidate(value)) {
        return callback(new Error('身份证号码错误'))
      }

      const isExist = await this.checkExist({
        'id_card.eq': value,
      })
      callback(isExist ? new Error('身份证号已存在') : void 0)
    }

    return {
      enumLoanGua,

      loading: false,
      tableName: 'market_project',
      form: {},
      rules: {
        address_name_pro: { required: true, trigger: 'blur', message: '请填写归属省' },
        address_name_city: { required: true, trigger: 'blur', message: '请填写归属市' },
        address_name_county: { required: true, trigger: 'blur', message: '请填写归属县' },
        org_class: { required: true, trigger: 'change', message: '请选择客户类型' },
        customer_name: {
          required: true,
          trigger: 'blur',
          message: '请填写受保企业名称或贷款人姓名',
        },
        corp_name: { required: true, trigger: 'blur', message: '请填写受保企业联系人姓名' },
        corp_phone: [
          { required: true, trigger: 'blur', message: '请填写受保企业联系人电话' },
          { validator: phoneValidator, trigger: 'blur', message: '请填写正确的联系人电话' },
        ],
        is_cert_merge: { required: true, trigger: 'change', message: '请选择是否三证合一' },
        register_no: [
          { required: true, trigger: 'blur', message: '请填写统一社会信用代码' },
          { validator: registerValidator, trigger: 'blur' },
        ],
        id_card: [
          { required: true, trigger: 'blur', message: '请填写身份证号码' },
          { validator: idCardValidator, trigger: 'blur' },
        ],
      },
    }
  },
  computed: {
    tableId() {
      return this.formData.customer_related_id
    },
    isIndividual() {
      const { org_class: orgClass } = this.form
      return ['org_farmer', 'org_farm', 'org_large_breed'].includes(orgClass)
    },
  },
  watch: {
    visible(val) {
      this.innerVisible = val
      if (val) {
        this.init()
      }
    },
  },
  created() {},
  mounted() {},
  methods: {
    init() {
      this.form = { ...this.formData }
      this.$nextTick(() => {
        this.$refs.form.clearValidate()
      })
    },

    beforeClose() {
      this.$emit('update:visible', false)
    },

    async checkExist(params) {
      this.loading = true
      const [res] = await this.$utils.promise(
        this.$api.getData(this.$serviceName, this.tableName, {
          index: 1,
          size: 1,
          ...params,
        })
      )
      this.loading = false
      const data = (res && res.data && res.data.data) || []
      return data.length && data[0].customer_related_id === this.tableId
    },

    handleOrgClassSelect(name) {
      this.form.org_class_name = name
    },

    handleSubmit() {
      this.$refs.form.validate((valid, obj = {}) => {
        if (!valid) {
          this.$message.error(convertFormErrMsg(obj))
        } else {
          this.putData()
        }
      })
    },

    putData() {
      this.loading = true
      this.$api
        .updateData(this.$serviceName, this.tableName, this.tableId, this.form)
        .then(res => {
          this.$message.success(`修改成功！`)
          this.$emit('success', res)
          this.beforeClose()
        })
        .catch(() => {
          this.$message.success(`修改失败，请重试！`)
        })
        .finally(() => {
          this.loading = false
        })
    },
  },
}
</script>

<style lang="scss" scoped></style>
